package com.keda.dao;

import com.keda.model.User;
import com.keda.util.DBUtil;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;

public class UserDao {

    public User findByUsernamePassword(String username, String password) {
        Connection connection = DBUtil.createConnection();
        String sql = "select id, username from t_user where username = ? and password = ?";
        QueryRunner queryRunner = new QueryRunner();
        try {
            User user = queryRunner.query(connection, sql, new BeanHandler<>(User.class),
                    username, password);
            return user;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }


    public User findByUsername(String username) {

        Connection connection = DBUtil.createConnection();
        String sql = "select id, username from t_user where username = ?";
        QueryRunner queryRunner = new QueryRunner();
        try {
            User user = queryRunner.query(connection, sql, new BeanHandler<>(User.class),
                    username);
            return user;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Integer insert(String username, String password,
                          String sex, String birthday, String identityCode,
                          String email, String mobile, String address) {

        Connection connection = DBUtil.createConnection();
        String sql = "insert into t_user (address, birthday, dentityCode, " +
                "email, mobile, password, sex, status, trueName, userName) " +
                "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        QueryRunner queryRunner = new QueryRunner();
        try {
            BigInteger userId = queryRunner.insert(connection, sql, new ScalarHandler<>(),
                    address, birthday, identityCode, email,
                    mobile, password, sex, 1, username, username);
            return userId.intValue();
        } catch (SQLException ex) {
            try {
                // 如果插入失败，那么事务进行回滚
                DbUtils.rollback(connection);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
}
